package handlers

import (
	"app-platform/cache"
	"app-platform/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	xzl, _ := strconv.Atoi(c.PostForm("xzl"))
	if title == "" || content == "" || xzl == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.App{
		Title:   title,
		Content: content,
		Xzl:     xzl,
	}
	r := models.DB.Begin()
	redis_key := "add" + title
	cache.Rdb.Get(cache.Ctx, redis_key)
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		r.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	r.Commit()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	var app []models.App
	redis_key := "list"
	jsonData, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	models.DB.Find(&app)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": app,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var app models.App
	redis_key := "list"
	jsonData, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	err := models.DB.Where("id = ?", id).First(&app).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": app,
	})
	return
}

func Xz(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	xzl, _ := strconv.Atoi(c.PostForm("xzl"))
	if title == "" || content == "" || xzl == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.App{
		Title:   title,
		Content: content,
		Xzl:     xzl,
	}
	r := models.DB.Begin()
	redis_key := "add" + title
	cache.Rdb.Get(cache.Ctx, redis_key)
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		r.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	r.Commit()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
